package com.yzc.config;

import com.yzc.constants.MqConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.yzc.constants.MqConstants.DELAY_EXCHANGE_NAME;
import static com.yzc.constants.MqConstants.ORDER_UNPAID_QUEUE;

@Configuration
public class RabbitMQConfig {


    //自定义消息转换器
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    // 延迟交换机
    @Bean
    public Exchange orderDelayedExchange() {
        return ExchangeBuilder
                .directExchange(DELAY_EXCHANGE_NAME)
                .delayed() // 设置为延迟交换机
                .build();
    }

    // 未支付订单队列
    @Bean
    public Queue orderUnpaidQueue() {
        return new Queue(ORDER_UNPAID_QUEUE);
    }

    // 绑定未支付订单队列到交换机
    @Bean
    public Binding bindingUnpaidOrder(@Qualifier("orderUnpaidQueue") Queue orderUnpaidQueue,
                                      @Qualifier("orderDelayedExchange") Exchange orderDelayedExchange) {
        return BindingBuilder
                .bind(orderUnpaidQueue)
                .to(orderDelayedExchange)
                .with("order.unpaid")
                .noargs();
    }

    // 回滚库存交换机
    @Bean
    public Exchange rollbackInventoryExchange() {
        return ExchangeBuilder
                .directExchange(MqConstants.ROLLBACK_INVENTORY_EXCHANGE)
                .durable(true)
                .build();
    }

    // 回滚库存队列
    @Bean
    public Queue rollbackInventoryQueue() {
        return new Queue(MqConstants.ROLLBACK_INVENTORY_QUEUE);
    }

    // 绑定回滚库存队列到交换机
    @Bean
    public Binding bindingRollbackInventory(@Qualifier("rollbackInventoryQueue") Queue rollbackInventoryQueue,
                                            @Qualifier("rollbackInventoryExchange") Exchange rollbackInventoryExchange) {
        return BindingBuilder
                .bind(rollbackInventoryQueue)
                .to(rollbackInventoryExchange)
                .with("rollback.inventory")
                .noargs();
    }
}